package part_04_Multiple_Locks_Using_Synchronized_Code_Blocks;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Worker {

	Random random_number = new Random();

	Object lock1=new Object();
	Object lock2=new Object();
	
	List<Integer> list1 = new ArrayList<Integer>();
	List<Integer> list2 = new ArrayList<Integer>();

	public void stageOne() {

		synchronized (lock1) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			list1.add(random_number.nextInt(100));
		
		}
	
	}

	public void stageTwo() {

		synchronized (lock2) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			list2.add(random_number.nextInt(100));
	
		}
		
	}

	void process() {

		for (int i = 0; i < 1000; i++) {
			stageOne();
			stageTwo();

		}

	}

	public void main1() {

		System.out.println("Starting Process...");
		long start = System.currentTimeMillis();

		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				process();

			}
		});

		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				process();

			}
		});

		t1.start();
		t2.start();
		
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long finish = System.currentTimeMillis();

		System.out.println("Time Taken :" + (finish - start));
		System.out.println("List1_size :" + list1.size() + "  "
				+ "List2_size :" + list2.size());

	}

}
